package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper mapper;

    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void save(Employee record) {
        mapper.insert(record);
        List<Role> roles = record.getRoles();
        if (roles != null){
            for (Role role : roles){
                //保存员工与角色的关系
                mapper.saveEmpRoleRelation(record.getId(),role.getId());
            }
        }
    }

    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Employee> list() {
        return mapper.selectAll();
    }

    public void update(Employee record) {
        mapper.updateByPrimaryKey(record);
        //先删除员工与角色的关系
        mapper.deleteEmpRoleRelation(record.getId());
        List<Role> roles = record.getRoles();
        if (roles != null){
            for (Role role : roles){
                //再保存员工与角色的关系
                mapper.saveEmpRoleRelation(record.getId(),role.getId());
            }
        }

    }

    //分页/高级查询
    public PageResult query(EmployeeQueryObject qo){
        int count = mapper.queryForCount(qo);
        List<Employee> employeeList = mapper.queryForList(qo);
        if (count==0){
            return new PageResult();
        }
        return new PageResult(count,employeeList);
    }

    //更改员工状态
    public void changeState(Long id){
        mapper.changeState(id);
    }

    public List<Employee> queryEmployee() {
       return  mapper.queryEmployee( );
    }

    public Employee checkName(String username) {
        return mapper.checkName(username);
    }

}
